package com.shadt.cloud.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.shadt.cloud.dao.SMSConfigDao;
import com.shadt.cloud.dao.SMSRecordDao;
import com.shadt.cloud.service.SMSService;
import com.shadt.sms.entity.SysSmsConfig;
import com.shadt.sms.entity.SysSmsRecord;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

/**
 * 短信业务逻辑层实现类
 * @author SongR
 *
 */
@Service("smsserviceimpl")
public class SMSServiceImpl implements SMSService{

	@Autowired
	SMSConfigDao dao;
	@Autowired	
	SMSRecordDao rdao;
	
	public SysSmsRecord send(String phone) throws Exception {
		SysSmsConfig config = dao.getR("smsconfig");
		if(null==config){
			List<SysSmsConfig> sc = dao.find("from SysSmsConfig where status = 0 order by id");
			if(sc.size()>0){
				config=sc.get(0);
				dao.addR("smsconfig", config);
			}
		}
		String checknum = (new Random().nextInt(8999) + 1000)+"";
		TaobaoClient client = new DefaultTaobaoClient(config.getUrl(),config.getUserid(),config.getPassword(),"json");
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend( "" );
		req.setSmsType( "normal" );
		req.setSmsFreeSignName(config.getAccount());
		req.setSmsParamString( "{code:'"+checknum+"'}" );
		req.setRecNum(phone);
		req.setSmsTemplateCode(config.getContent());
		SysSmsRecord record = null;
		try {
			AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
			JSONObject j = JSONObject.parseObject(rsp.getBody());
			if(j.get("alibaba_aliqin_fc_sms_num_send_response")!=null&&!"".equals(j.get("alibaba_aliqin_fc_sms_num_send_response"))){
				List<SysSmsRecord> rs = rdao.find("from SysSmsRecord where status=1 and phone='"+phone+"'");
				for (SysSmsRecord sss : rs) {
					sss.setStatus(-1);
					rdao.update(sss);
				}
				record=new SysSmsRecord();
				record.setCode(checknum+"");
				record.setPhone(phone);
				record.setSendtime(new Date());
				record.setStatus(1);
				rdao.save(record);
				rdao.addR(phone+checknum,record);
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return record;
	}

	@Override
	public boolean invalid(Long id) throws Exception {
		SysSmsRecord r = rdao.get(SysSmsRecord.class, id);
		if(null!=r){
			r.setStatus(-1);
			rdao.update(r);
			rdao.deleteR(r.getPhone());
		}
		return true;
	}

	@Override
	public boolean checkCode(String phone, String code) throws Exception {
		SysSmsRecord r = rdao.getR(phone+code);
		if(null!=r){
			return true;
		}
		return false;
	}

}
